package com.supersit.greensproject.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

import com.supersit.greensproject.DB.XUtilsDbManager;
import com.supersit.greensproject.R;
import com.supersit.greensproject.entity.UpdateInfo;
import com.supersit.greensproject.entity.User;
import com.supersit.greensproject.resources.API;
import com.supersit.greensproject.utils.AppUtils;
import com.supersit.greensproject.utils.DBut;
import com.supersit.greensproject.utils.DesUtil;
import com.supersit.greensproject.utils.HttpXUtils;
import com.supersit.greensproject.utils.L;
import com.supersit.greensproject.utils.MyCallBack;
import com.supersit.greensproject.utils.NetUtils;
import com.supersit.greensproject.utils.SPUtils;
import com.supersit.greensproject.utils.T;
import com.supersit.greensproject.utils.UpdateManager;
import com.supersit.greensproject.view.ShowDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cong on 2016/7/12.
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
    public String TAG = LoginActivity.class.getSimpleName();
    @ViewInject(R.id.et_user_name)
    private EditText etUserName;
    @ViewInject(R.id.et_user_pwd)
    private EditText etPassword;
    @ViewInject(R.id.btn_login)
    private Button btnLogin;
    @ViewInject(R.id.cb_remember_password)
    private CheckBox cbRememberPassword;
    private User user;
    //    private String userName;
//    private String password;
    private Context context;
    private ShowDialog showDialog;
    //当前版本号
    private String localVersion;
    //服务器的版本信息
    private UpdateInfo updateInfo;
    /* Message handler */
    private final static int UPDATE_NONEED = 0;
    private final static int UPDATE_CLIENT = 1;
    private final static int GET_UNDATEINFO_ERROR = 2;
    private final static int LOGIN_SUCCESS = 4;
    private final static int LOGIN_FAIL = 3;
    private final static int PASSWORK_ERROR = 5;
    private String updateApkUrl = "";

    private MyHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        context = this;
        SQLiteDatabase dbFile = DBut.openDatabase(context);
        dbFile.close();
        initVariable();
        bindListener();
    }

    private void initVariable() {
        boolean isRememberPassword = (boolean) SPUtils.get(context, "isRememberPassword", false);
        showDialog = new ShowDialog(context);
        if (isRememberPassword) {
            etUserName.setText((String) SPUtils.get(context, "username", ""));
            etPassword.setText((String) SPUtils.get(context, "password", ""));
            cbRememberPassword.setChecked(isRememberPassword);
        }
        handler = new MyHandler(this);
        //  checkUpgrade();//檢測版本更新
    }

    /**
     * 绑定监听事件
     */
    private void bindListener() {
        btnLogin.setOnClickListener(onClickListener);
    }

    /**
     * 点击事件监听
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_login:
                    if (checkData()) {
                        if (NetUtils.isConnected(context)) {
                            login(user);
                        } else {
                            T.showShort(context, R.string.net_not_connected);
                        }
                    }
//                    startActivity(new Intent(context, MainActivity.class));
//                    finish();
//                    break;
            }
        }
    };

    /**
     * 登陆方法
     *
     * @param user
     */
    private void login(final User user) {
        showDialog.showLoadingDialog(getString(R.string.logining));
        final String login_url = API.login;
        Map<String, Object> params = new HashMap<>();
        if (null != user) {
            params.put("account", user.getUsername());
            try {
                params.put("password", DesUtil.encrypt(user.getPassword(), (String) SPUtils.get(context, "key", "12345678")));
                //params.put("password", DesUtil.encrypt(user.getPassword(), "12345678"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            HttpXUtils.Post(login_url, params, new MyCallBack<String>() {

                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    showDialog.dismissLoadDialog();
                    L.d("result", result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        int isfalse = jsonObject.optInt("isfalse");
                        String resultMsg = jsonObject.optString("msg");
                        JSONObject resultdata = jsonObject.optJSONObject("resultdata");
                        String maketAuthority = "";//市场权限
                        String baseAuthority = "";//基地权限
                        String qualityMonitoringAuthority = "";//质量检测权限
                        String token = "";
                        int userId = 0;
                        if (null != resultdata) {
                            maketAuthority = TextUtils.isEmpty(resultdata.optString("market")) ? "" : resultdata.optString("market").trim();//市场权限
                            baseAuthority = TextUtils.isEmpty(resultdata.optString("subjectAuthority")) ? "" : resultdata.optString("subjectAuthority").trim();//基地权限
                            qualityMonitoringAuthority = TextUtils.isEmpty(resultdata.optString("qualityMonitoring")) ? "" : resultdata.optString("qualityMonitoring").trim();//质量检测权限
                            token = resultdata.optString("ydToken");
                            userId = resultdata.optInt("id");
                        }
                        if (0 == isfalse) {//帐号不存在
                            Message msg = new Message();
                            msg.obj = resultMsg;
                            msg.what = LOGIN_FAIL;
                            handler.sendMessage(msg);
                        } else if (1 == isfalse) {//登陆成功
                            SPUtils.put(context, "token", token);
                            SPUtils.put(context, "maketAuthority", maketAuthority);//
                            SPUtils.put(context, "baseAuthority", baseAuthority);
                            SPUtils.put(context, "qualityMonitoringAuthority", qualityMonitoringAuthority);
                            SPUtils.put(context, "username", user.getUsername());
                            SPUtils.put(context, "password", user.getPassword());
                            SPUtils.put(context, "isRememberPassword", user.isRememberPassword());
                            SPUtils.put(context, "userId", userId);
                            Message msg = new Message();
                            msg.obj = resultMsg;
                            msg.what = LOGIN_SUCCESS;
                            handler.sendMessage(msg);
                        } else if (2 == isfalse) {//帐号被锁定
                            Message msg = new Message();
                            msg.obj = resultMsg;
                            msg.what = LOGIN_FAIL;
                            handler.sendMessage(msg);
                        } else if (3 == isfalse) {//密码错误
                            Message msg = new Message();
                            msg.obj = resultMsg;
                            msg.what = PASSWORK_ERROR;
                            handler.sendMessage(msg);
                        } else if (4 == isfalse) {//系统异常
                            Message msg = new Message();
                            msg.obj = resultMsg;
                            msg.what = LOGIN_FAIL;
                            handler.sendMessage(msg);
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                        Message msg = new Message();
                        msg.obj = getString(R.string.data_error);
                        msg.what = LOGIN_FAIL;
                        handler.sendMessage(msg);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    L.e("error", ex.toString());
                    showDialog.dismissLoadDialog();
                    Message msg = new Message();
                    msg.obj = getString(R.string.service_error);
                    msg.what = LOGIN_FAIL;
                    handler.sendMessage(msg);
                }

            });
        } else {
            T.showShort(context, R.string.data_error);
        }
    }

    private boolean checkData() {
        boolean isRememberPassword = false;
        if (TextUtils.isEmpty(etUserName.getText().toString().trim())) {
            T.showShort(context, R.string.username_is_null);
            return false;
        }
        if (TextUtils.isEmpty(etPassword.getText().toString().trim())) {
            T.showShort(context, R.string.password_is_null);
            return false;
        }
        if (cbRememberPassword.isChecked()) {
            isRememberPassword = true;
        }
        user = new User();

        String userName = etUserName.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        user.setUsername(userName);
        user.setPassword(password);
        user.setRememberPassword(isRememberPassword);
        return true;
    }

    /**
     * 检查APP版本更新
     */
    private void checkUpgrade() {
        if (NetUtils.isConnected(context)) {
            try {
                localVersion = AppUtils.getVersionName(context);
                showDialog.showLoadingDialog(getString(R.string.check_version_ing));
                String url = API.checkVersion;
                HttpXUtils.Get(url, null, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        showDialog.dismissLoadDialog();
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            updateInfo = new UpdateInfo();
                            updateInfo.setVersion(jsonObject.optString("version"));
                            updateInfo.setUrl(jsonObject.optString("url"));
                            updateInfo.setDescription(jsonObject.optString("description"));
                            String key = jsonObject.optString("deskey");
                            if (!TextUtils.isEmpty(key)) {
                                SPUtils.put(context, "key", key);
                            }
                            if (updateInfo.getVersion().equals(localVersion)) {
                                // 版本号相同，无需升级
                                Message msg = new Message();
                                msg.obj = updateInfo;
                                msg.what = UPDATE_NONEED;
                                handler.sendMessage(msg);
                            } else {
                                // 版本号不同 ,提示用户升级
                                updateApkUrl = updateInfo.getUrl();
                                Message msg = new Message();
                                msg.what = UPDATE_CLIENT;
                                handler.sendMessage(msg);
                            }

                        } catch (JSONException e) {
                            showDialog.dismissLoadDialog();
                            // 待处理
                            Message msg = new Message();
                            msg.what = GET_UNDATEINFO_ERROR;
                            handler.sendMessage(msg);
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        showDialog.dismissLoadDialog();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        super.onCancelled(cex);
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                    }
                });


            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            T.showShort(context, R.string.not_connected);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private class MyHandler extends Handler {
        DbManager db = XUtilsDbManager.getInstance();
        WeakReference<LoginActivity> mActivity;

        MyHandler(LoginActivity activity) {
            mActivity = new WeakReference<LoginActivity>(activity);
        }

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LoginActivity theActivity = mActivity.get();
            switch (msg.what) {
                case UPDATE_NONEED://无需升级
                    try {
                        UpdateInfo mUpdateInfo = db.selector(UpdateInfo.class).orderBy("id", true).findFirst();
                        if (null != mUpdateInfo) {
                            if (updateInfo.getVersion().equals(mUpdateInfo.getVersion())) {
                                mUpdateInfo.setDescription(updateInfo.getDescription());
                                mUpdateInfo.setUrl(updateInfo.getUrl());
                                db.update(mUpdateInfo, "description", "url");
                            }
                        } else {
                            db.saveBindingId(updateInfo);
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }


                    break;
                case GET_UNDATEINFO_ERROR:
                    // 服务器超时
                    T.showShort(context, R.string.get_update_error);
                    break;
                case UPDATE_CLIENT:
                    // 对话框通知用户升级程序
                    theActivity.showUpdateDialog();
                    break;
                case LOGIN_SUCCESS:
                    T.showShort(context, (String) msg.obj);
                    startActivity(new Intent(context, MainActivity.class));
                    finish();
                    break;
                case LOGIN_FAIL:
                    T.showShort(context, (String) msg.obj);
                    break;
                case PASSWORK_ERROR:
                    T.showShort(context, (String) msg.obj);
                    break;
            }
        }
    }

    /**
     * 弹出对话框通知用户更新程序
     */
    protected void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.version_upgrade));
        builder.setMessage(updateInfo.getDescription());
        builder.setPositiveButton(getString(R.string.common_confirm),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (!TextUtils.isEmpty(updateApkUrl)) {
                            UpdateManager updateManager = new UpdateManager(
                                    context, updateApkUrl);
                            updateManager.checkUpdateInfo();
                        }
                    }
                });
        builder.setNegativeButton(getString(R.string.common_cancel),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
